

import subprocess
import json


# curl -X POST http://10.244.0.152:5001/api/task/create 
#       -H "Content-Type: application/json" 
#       -d '{"requirements":{"cpu": {"cpu_usage": 31.1, "cpu_count": 32, "cpu_freq": 2384.36153125}, "memory": {"memory_total": 134659764224, "memory_available": 113606070272, "memory_used": 19749892096, "memory_percent": 15.6}, "disk": {"disk_total": 1947177910272, "disk_free": 1651186610176, "disk_used": 197004574720, "disk_percent": 10.7}, "gpu": {"gpu_memory_free":12415923815}, "links": [{"sat_id": 2, "time": 5}, {"sat_id": 4, "time": 5}, {"sat_id": 20, "time": 5}, {"sat_id": 22, "time": 5}]}, "sliceCount": 5}'


def run_command(command):
    """
    运行命令行并捕获输出
    :param command: 要运行的命令
    :return: 命令输出
    """
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"Error running command: {command}\n{e.stderr.strip()}")
        return None

def curl_command(command):
    exe_command = "curl " + command
    return run_command(exe_command)



def generate_curl_command(base_url, endpoint, method, headers, data):
    """
    根据配置生成 curl 命令字符串
    
    :param base_url: str - API 基础 URL，例如 "http://192.1.1.1:5001"
    :param endpoint: str - API 端点，例如 "/api/task/create"
    :param method: str - HTTP 方法，例如 "POST"
    :param headers: dict - 请求头部，例如 {"Content-Type": "application/json"}
    :param data: dict - 请求体数据（JSON 格式）
    :return: str - 生成的 curl 命令字符串
    """
    # 将 headers 转换为 curl 格式
    headers_str = " ".join([f'-H "{key}: {value}"' for key, value in headers.items()])
    
    # 将 JSON 数据转换为字符串（并转义双引号）
    data_str = json.dumps(data).replace('"', '\\"')
    
    # 拼接 curl 命令
    # curl_command = f'''curl -X {method} {base_url}{endpoint} {headers_str} -d "{data_str}"'''
    curl_command = f'''-X {method} {base_url}{endpoint} {headers_str} -d "{data_str}"'''
    
    return curl_command
